package cn.ddiancan.xddcloud.common.interceptor;

import cn.ddiancan.xddcloud.common.context.CloudRequestContext;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.util.Objects;

/**
 * 调用外部请求，需要传出去的请求头拦截器
 *
 * @author Amos
 */
public class OutgoingRequestInterceptor implements ClientHttpRequestInterceptor, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
        // 部分请求，headers为ReadOnly类型
        HttpHeaders headers = request.getHeaders();
        HttpRequestWrapper httpRequestWrapper = new HttpRequestWrapper(request);
        HttpHeaders newHeaders = new HttpHeaders();
        if (CloudRequestContext.isCurrentThreadInitialized()) {
            MultiValueMap<String, String> outGoing = Objects.requireNonNull(
                CloudRequestContext.getContextForCurrentThread()).getOutGoing();
            outGoing.putAll(headers);
            outGoing.forEach((k, v) -> {
                if (!headers.containsKey(k)) {
                    newHeaders.put(k, v);
                }
            });
            httpRequestWrapper.getHeaders().putAll(newHeaders);
        }
        return execution.execute(httpRequestWrapper, body);
    }
}
